<?php declare(strict_types=1);

namespace Itdashu\Token\Bean;

use Swoft\Bean\Annotation\Mapping\Bean;
use Swoft\Context\Context;
use Swoft\Redis\Pool;
use Swoft\Stdlib\Helper\StringHelper;
use Swoft\Bean\Annotation\Mapping\Inject;
use RuntimeException;

/**
 * Class Token
 * @package Itdashu\Token\Bean
 * @Bean(scope=Bean::REQUEST)
 */
class Token
{
  /**
   * @var
   */
  protected $token;

  /**
   * @var string
   */
  protected $basePrefix = 'token_';

  /**
   * @var
   */
  protected $userPrefix;

  /**
   * @Inject()
   *
   * @var Pool
   */
  private $redis;

  /**
   * @return $this
   * @throws \Swoft\Exception\SwoftException
   */
  public function init():self
  {
    $request = \context()->getRequest();
    if (!$request->hasHeader('token')) {
      throw new RuntimeException('请求构造非法');
    }
    $this->setToken($request->getHeaderLine('token'));
    return $this;
  }

  /**
   * @param string $token
   * @return $this
   */
  public function setToken(string $token): self
  {
    if (!$token) {
      $this->token = $token;
      $this->userPrefix = $this->basePrefix . $this->token . '_';
    }
    return $this;
  }

  /**
   * @param $key
   * @param null $value
   * @return $this
   */
  public function set($key, $value = null): self
  {
    if ($value === null) {
      $this->redis->set($this->userPrefix, \Itdashu\Token\Library\TokenHelper::encode($key));
    } else {
      $this->redis->set($this->userPrefix . $key, \Itdashu\Token\Library\TokenHelper::encode($value));
    }
    return $this;
  }

  /**
   * @param $key
   * @param $value
   * @return Token
   */
  public function update($key, $value): self
  {
    $output = $this->get($key);
    if (!is_array($output)) {
      $this->del($key);
      $output = [];
    }
    $output = array_merge($output,$value);
    $this->set($key, $output);
    return $this;
  }

  /**
   * @param $key
   * @return bool
   */
  public function del($key):bool
  {
    return (bool)$this->redis->del($this->userPrefix . $key);
  }

  /**
   * @param string $key
   * @return mixed
   */
  public function get(string $key = '')
  {
    return \Itdashu\Token\Library\TokenHelper::decode($this->redis->get($this->userPrefix . $key));
  }
}